package groep3.ssc.tmts;

import groep3.ssc.controllers.ModelRepository;
import groep3.ssc.controllers.ViewController;
import groep3.ssc.model.Race;
import groep3.ssc.model.Skater;
import groep3.ssc.model.Skater.Lane;

import java.util.EventListener;

import org.json.JSONObject;

public class TMTSListener implements EventListener
{
    private Race model;
    TMTSRunnable tmts_r;
    Thread tmts_r_thread;

    public TMTSListener()
    {
        tmts_r = new TMTSRunnable(this);
        tmts_r_thread = new Thread(tmts_r);
        tmts_r_thread.start();
    }

    public void givePulse(String input)
    {
        try
        {
            model = ModelRepository.getInstance().getActiveRace();
            if (model == null)
                return;

            JSONObject jObject = new JSONObject(input);

            System.out.println("Cur skater" + jObject.getInt("ID"));
            Skater skater = model.getSkater(jObject.getInt("ID"));
            if (skater == null)
            {
                skater = new Skater();
                model.addSkater(jObject.getInt("ID"), skater);
            }
            skater.setName(jObject.getString("name"));
            skater.setLane(switchLane(skater.getLane()));
            skater.addLap(jObject.getLong("laptime"));
            skater.setTotalTime(jObject.getLong("time"));
            skater.setTotalDistance(jObject.getInt("distance"));
            ViewController.getInstance().update();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private Lane switchLane(Lane lane)
    {
        if (lane == Lane.INNER)
            return Lane.OUTER;
        return Lane.INNER;
    }
}
